<template>
	<view class="uni-container" v-show="isShow">
		<uni-forms ref="form" :value="formData" validateTrigger="bind">
			<uni-forms-item name="imei" label="设备编号:">
				<view style="vertical-align: middle;font-size:16px;margin-top: 8px;">{{formData.imei}}</view>
			</uni-forms-item>
			<uni-forms-item name="name" label="设备名称:" required>
				<uni-easyinput placeholder="请为您的设备起个名字" v-model="formData.name"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="openid" label="微信号:" v-show="false">
				<uni-easyinput placeholder="微信号" v-model="formData.openid"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="interval" label="报警间隔(分钟):">
				<uni-number-box :min="2" :max="120"  background="#2979FF" color="#fff" v-model="formData.interval"></uni-number-box>
			</uni-forms-item>
			<uni-forms-item name="num" label="报警次数:">
				<uni-number-box :min="1" :max="6"  background="#2979FF" color="#fff" v-model="formData.num"></uni-number-box>
			</uni-forms-item>
			<uni-forms-item name="tel1" label="报警电话1:">
				<uni-easyinput placeholder="请输入接收通知的电话号码" v-model="formData.tel1"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="tel2" label="报警电话2:">
				<uni-easyinput placeholder="请输入接收通知的电话号码" v-model="formData.tel2"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="tel3" label="报警电话3:">
				<uni-easyinput placeholder="请输入接收通知的电话号码" v-model="formData.tel3"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="iswx" label="微信通知(免费):">
				<switch :checked="formData.iswx" v-model="formData.iswx" @change="switchChangeWx" />
			</uni-forms-item>
			<uni-forms-item name="issms" label="短信通知(0.1元/次):">
				<switch :checked="formData.issms" v-model="formData.issms" @change="switchChangeSms" />
			</uni-forms-item>
			<uni-forms-item name="isvms" label="电话通知(0.1元/次):">
				<switch :checked="formData.isvms" v-model="formData.isvms" @change="switchChangeVms" />
			</uni-forms-item>



			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 70%;margin-left: 20%;"
					@click="submit">提交保存</button>
				<!-- 	<button class="uni-button" style="width: 100px;" @click="f_close">返回</button> -->

			</view>
		</uni-forms>
		<uni-pay ref="pay" :adpid="adpid" return-url="/pages/order-detail/order-detail" logo="/static/logo.png"
			@success="onSuccess" @create="onCreate"></uni-pay>
	</view>
</template>
<script>
	import wx from '@/uni_modules/weixin-jsapi/index.js'
	import sign from './scan.js'
	let appId = 'wx762857d4ca0523c5'
	let timestamp = Date.parse(new Date()) / 1000;
	let nonceStr = 'nonceStrtest'
	let url = '';
	let ua = navigator.userAgent.toLowerCase();
	url = window.location.href.split('#')[0]; //获取到的url是当前页面的域名
	const db = uniCloud.database();
	const dbCmd = db.command;
	const dbCollectionName = 'a-device';
	export default {
		// 数据属性
		data() {
			return {
				formData: {

				},
				openid: '',
				isShow: false,
				// 搜索值
				searchVal: '',
				// 表格数据
				tableData: [],
				// 每页数据量
				pageSize: 10,
				// 当前页
				pageCurrent: 1,
				// 数据总量
				total: 2222,
				// 加载状态
				loading: false
			}
		},
		async onLoad(options) {
		},
		async onReady(options = {}) {
			const that = this
			var url = window.location.href; //获取当前url
			var dz_url = url.split('#')[0]; //获取#/之前的字符串
			var cs = dz_url.split('?')[1]; //获取?之后的参数字符串
			if (cs) {
				var cs_arr = cs.split('&'); //参数字符串分割为数组
				var cs = {};
				for (var i = 0; i < cs_arr.length; i++) { //遍历数组，拿到json对象
					cs[cs_arr[i].split('=')[0]] = cs_arr[i].split('=')[1]
				}
				}
				// 获取微信公众号的openid
					await this.getOpenid({
						provider: "wxpay",
						code: cs.code
					});
					uniCloud.callFunction({
						name: 'uni-ticket'
					}).then(res => {
						let token = res.result.token
						let jsticket = res.result.ticket
						let signature = sign.getSign(jsticket, nonceStr, timestamp, url)
						wx.config({
							debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
							appId: appId, // 必填，公众号的唯一标识
							timestamp: timestamp, // 必填，生成签名的时间戳
							nonceStr: nonceStr, // 必填，生成签名的随机串
							signature: signature, // 必填，签名
							jsApiList: ["scanQRCode"] // 必填，需要使用的JS接口列表
						});
						wx.ready(function() {
							wx.scanQRCode({
								desc: 'scanQRCode desc',
								needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
								scanType: ["qrCode"],
								success: function(res) {
									that.getInfo(res.resultStr.substr(0, 15))
								}
							});
						});
					}).catch((err) => {
						console.error(err)
					})


				
			




		},
		methods: {
			submit() {
				uni.showLoading({
					mask: true
				})
				this.$refs.form.validate().then((res) => {

					let res_sub = this.submitForm(res)
					return res_sub
				}).catch(() => {}).finally(() => {
					uni.hideLoading()
					// uni.showToast({
					// 	title: '配置成功',
					// 	//显示持续时间为 2秒
					// 	duration: 8000,
					// 	success: () => {
					// 		this.f_close()
					// 	}
					// })
					uni.showModal({
						content: '配置成功',
						showCancel: false,
						success: () => {
							this.f_close()
						}
					})
					
					

				})
			},
			switchChangeWx: function(event) {
				this.formData.iswx = event.detail.value; // 获取开关状态
			},
			switchChangeSms: function(event) {
				this.formData.issms = event.detail.value; // 获取开关状态
			},
			switchChangeVms: function(event) {
				this.formData.isvms = event.detail.value; // 获取开关状态
			},
			/**
			 * 提交表单
			 */
			async submitForm(value) {
				let res = await db.collection(dbCollectionName).where({
					imei: value.imei
				})

				// 使用 clientDB 提交数据
				return db.collection(dbCollectionName).where({
					imei: value.imei
				}).update(value).then((res) => {
					// uni.showToast({
					// 	title: '配置成功',
					// 	//显示持续时间为 2秒
					// 	duration: 3000
					// })

				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
				})
			},
			async getInfo(imei) {
				this.isShow = true
				// uni.showLoading({
				// 	mask: true
				// })

				await db.collection(dbCollectionName)
					.where({
						imei: imei
					})
					.field("imei,name,openid,interval,num,iswx,issms,isvms,tel1,tel2,tel3")
					.get().then((res) => {
						//alert(JSON.stringify(res))
						if (res.result.data.length == 0) {

							uni.showModal({
								content: '数据不存在，请联系客服处理',
								showCancel: false,
								success: () => {
									this.f_close()
								}
							})
						}
						const data = res.result.data[0]
						if (data) {
							if (data.openid) {
								if (data.openid == this.openid) {
									this.formData = data
								} else {
									alert("没有权限，请联系客服人员授权处理")
									this.f_close();
								}
							} else {
								data.openid = this.openid
								this.formData = data
							}
						}
					}).catch((err) => {
						uni.showModal({
							content: err.message || '请求服务失败',
							showCancel: false
						})
					}).finally(() => {
						// uni.hideLoading()
					})

			},
			f_close() {
				if (typeof(WeixinJSBridge) != "undefined") {
					WeixinJSBridge.call('closeWindow');
				} else {
					if (navigator.userAgent.indexOf("MSIE") > 0) {
						if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {
							window.opener = null;
							window.close();
						} else {
							window.open('', '_top');
							window.top.close();
						}
					} else if (navigator.userAgent.indexOf("Firefox") > 0) {
						window.location.href = 'about:blank ';
					} else {
						window.opener = null;
						window.open('', '_self', '');
						window.close();
					}
				}
			},

			// 获取公众号code
			async getWeiXinJsCode(scope = "snsapi_base") {

				let redirect_uri = encodeURIComponent(window.location.href.split("?")[0]);
				let url =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&response_type=code&scope=${scope}&redirect_uri=${redirect_uri}&state=STATE#wechat_redirect`;
							
				window.location.href = url;


			},
			// 获取公众号openid
			async getOpenid(data) {
				let res = await this.$refs.pay.getOpenid(data);
				if (res) {
					this.openid = res.openid
				}
			}

		}
	}
</script>
<style>
	*{
	font-size: 18px;
	font-weight:bold;
	font-family: "微软雅黑";
	}
	::v-deep .uni-forms-item__label {
		width: 140px !important;
	}

	.uni-container {
		margin: 15px
	}

	switch {
		float: right
	}
</style>